package com.rectcircle.wechat.api;

import java.util.Map;
import java.util.UUID;

import com.rectcircle.wechat.exception.ApiRequestErrorException;
import com.rectcircle.wechat.exception.ConfigException;
import com.rectcircle.wechat.ret.vo.BasicReturn;
import com.rectcircle.wechat.util.CharTools;
import com.rectcircle.wechat.util.Constants;
import com.rectcircle.wechat.util.HttpRequest;
import com.rectcircle.wechat.util.JsonHandler;
import com.rectcircle.wechat.util.SecurityAlgorithm;
import com.rectcircle.wechat.vo.WxJsConfig;

/**
 * 
 * 
 * 
 * @author RectCircle
 * @version 0.1<br>
 * 2016年7月26日-下午1:40:24<br>
 * Copyright (c) 2016 RectCircle-版权所有<br>
 *
 */
//TODO 未进行实际测试
public class WebApi {
	
	public static final String Scope_Type_BASE = "snsapi_base";
	
	public static final String Scope_Type_USERINFO= "snsapi_userinfo";
	
	/**
	 * 
	 * 获得构造好的OAuth2Url<br>
	 * 
	 * 注意：如果微信客户端测试出现redirect_uri错误请到开发者中心填写 网页授权获取用户基本信息{@code ->}修改授权回调页面域名:
	 * 
	 * @param appid 微信appid
	 * @param redirect_uri 需要授权的页面
	 * @param scope 获得用户消息的类型，取值为 ：仅获取openid："snsapi_base"，获取用户信息："snsapi_userinfo"
	 * @param state 将会传给需要授权页面的参数
	 * @return 构造好的OAuth2Url
	 * @throws ConfigException 参数异常
	 */
	public static String getOAuth2Url(String appid, String redirect_uri, String scope, String state) throws ConfigException{
		String api = Constants.getApi("OAuth2Url");
		
		if(scope!=Scope_Type_BASE&&scope!=Scope_Type_USERINFO){
			throw new ConfigException("scope："+scope+" scope的取值只能为："+Scope_Type_BASE+" 和 "+Scope_Type_USERINFO);
		}
		
		String url = String.format(api, appid, CharTools.urlEncode(redirect_uri),scope,state);
		return url;
	}
	
	
	public static String getOpenidByCode(String appid, String secret, String code) throws ApiRequestErrorException{
		String api = Constants.getApi("getOpenidByCode");
		String url = String.format(api, appid, secret,code);
		HttpRequest httpRequest = new HttpRequest.Builder(url)
				.build();
		String responseJson = httpRequest.getHtmlByGet();
		
		Map<String, Object> retMsg = JsonHandler.parseJson(responseJson, Map.class);
		if(retMsg.get("errcode")!=null){
			throw new ApiRequestErrorException(JsonHandler.parseJson(responseJson, BasicReturn.class).getErrDescription());
		}
		return (String) retMsg.get("openid");
	}
	
	/**
	 * 
	 * 获得JSSDK注入权限验证配置对象<br>
	 * 得到对象后需要调用addJsApi()方法添加需要调用的js接口列表
	 * 
	 * 
	 * @param debug 是否配置为debug模式
	 * @param jsApiTicket 调用微信JS接口的临时票据
	 * @param appId 微信appId
	 * @param url 需要用到微信JSSDK的页面url
	 * @return WxJsConfig对象
	 */
	public static WxJsConfig createWxJsConfig(boolean debug,String jsApiTicket, String appId, String url){
		String nonceStr = UUID.randomUUID().toString();
		long timestamp = System.currentTimeMillis() / 1000;
		String src = "jsapi_ticket=" + jsApiTicket +
				"&noncestr=" + nonceStr + 
				"&timestamp=" + timestamp + 
				"&url=" + url;

		String signature = SecurityAlgorithm.encryptBySHA1(src);
		return new WxJsConfig(debug, appId, timestamp, nonceStr, signature);
	}
	
	/**
	 * 
	 * 获得JSSDK注入权限验证配置对象字符串（接口列表添加全部接口）<br>
	 * 示例：<br>
	 * <pre>
	 * {@code //当调用}
	 * {@code //jsApiTicket通过obtainJsApiTicket()获得，}
	 * String config = WebApi.createWxJsConfigString(false, jsApiTicket, "wx7ea1430521f010d9", "http://www.baidu.com");
	 * System.out.println(config);
	 * {@code //打印如下(格式化后的结果)}
	 * wx.config({
	 * 	debug: false,
	 * 	appId: 'wx7ea1430521f010d9',
	 * 	timestamp: 1469541396,
	 * 	nonceStr: 'a16b974e-6e5a-4bf8-8215-256a1f3c2679',
	 * 	signature: 'eade71258802528e2daaf9bf120c5728d476c552',
	 * 	jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice', 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'translateVoice', 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'closeWindow', 'scanQRCode', 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard']
	 * });
	 * </pre>
	 * 
	 * @param debug 是否配置为debug模式
	 * @param jsApiTicket 调用微信JS接口的临时票据
	 * @param appId 微信appId
	 * @param url 需要用到微信JSSDK的页面url
	 * @return WxJsConfig字符串
	 */
	//TODO 未实际测试
	public static String createWxJsConfigString(boolean debug,String jsApiTicket, String appid, String url){
		WxJsConfig jsConfig = createWxJsConfig(debug,jsApiTicket, appid, url);
		jsConfig.addAllJsApi();
		return jsConfig.toString();
	}
	
}
